package com.youku.monitor;

import java.io.File;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.config.Action;
import com.youku.config.XmlReader;

public class LogMonitor {

	private static final Logger logger = LoggerFactory.getLogger(LogMonitor.class);

	public void start() {
		long intervalSecond = Long.parseLong(XmlReader.getProperty("interval"));
		logger.info("轮询间隔时间为{}秒", intervalSecond);
		long intervalMilisecond = TimeUnit.SECONDS.toMillis(intervalSecond);

		for (Entry<String, Action> actions : XmlReader.getActions().entrySet()) {
			String name = actions.getKey();
			Action action = actions.getValue();

			logger.info("监听目录{}下日志内容的变动", action.getPath());

			File directory = new File(action.getPath());

			// 创建一个文件观察器用于处理文件的格式
			FileAlterationObserver observer = new FileAlterationObserver(directory);
			// 设置文件变化监听器
			observer.addListener(new LogListener(name));
			FileAlterationMonitor monitor = new FileAlterationMonitor(intervalMilisecond, observer);
			try {
				monitor.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		new LogMonitor().start();
	}
}
